package com.cloudOffice.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cloudOffice.model.system.SysUser;
import com.cloudOffice.result.Result;
import com.cloudOffice.service.SysUserService;
import com.cloudOffice.utils.JwtUtils;
import com.cloudOffice.vo.wechat.BindPhoneVo;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@Slf4j
@Tag(name = "微信登录管理")
@RestController("WechatController")
@RequestMapping("/admin/wechat")
@CrossOrigin //跨域
public class WechatController {
	
	@Resource
	private SysUserService sysUserService;
	@Resource
	private WxMpService wxMpService;
	@Value("${wechat.userInfoUrl}")
	private String userInfoUrl;
	
	@GetMapping("/authorize")
	public String authorize(@RequestParam("returnUrl") String returnUrl,
	                        HttpServletRequest request) {
		//buildAuthorizationUrl三个参数
		//第一个参数：授权路径，在哪个路径获取微信信息
		//第二个参数：固定值，授权类型 WxConsts.OAuth2Scope.SNSAPI_USERINFO
		//第三个参数：授权成功之后，跳转路径  'guiguoa' 转换成  '#'
		String redirectUrl = null;
		try {
			redirectUrl = wxMpService.getOAuth2Service()
					.buildAuthorizationUrl(userInfoUrl,
							WxConsts.OAuth2Scope.SNSAPI_USERINFO,
							URLEncoder.encode(returnUrl.replace("guiguoa", "#"), "utf-8"));
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
		return "redirect:" + redirectUrl;
	}
	
	@GetMapping("/userInfo")
	public String userInfo(@RequestParam("code") String code,
	                       @RequestParam("state") String returnUrl) throws Exception {
		//获取accessToken
		WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
		
		//使用accessToken获取openId
		String openId = accessToken.getOpenId();
		
		//获取微信用户信息
		WxOAuth2UserInfo wxMpUser = wxMpService.getOAuth2Service().getUserInfo(accessToken, null);
		log.info("微信用户信息: " + JSON.toJSONString(wxMpUser));
		
		SysUser sysUser = sysUserService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getOpenId, openId));
		String token = "";
		//判断openid是否存在
		if (sysUser != null) {
			HashMap<String, Object> map = new HashMap<>();
			map.put("id", sysUser.getId());
			map.put("username", sysUser.getUsername());
			token = JwtUtils.create(map);
		}
		if (!returnUrl.contains("?")) {
			return "redirect:" + returnUrl + "?token=" + token + "&openId=" + openId;
		} else {
			return "redirect:" + returnUrl + "&token=" + token + "&openId=" + openId;
		}
	}
	
	@PostMapping("/bindPhone")
	@ResponseBody
	public Result<String> bindPhone(@RequestBody BindPhoneVo bindPhoneVo) {
		//1 根据手机号查询数据库
		LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(SysUser::getPhone, bindPhoneVo.getPhone());
		SysUser sysUser = sysUserService.getOne(wrapper);
		
		//2 如果存在，更新记录 openid
		if (sysUser != null) {
			sysUser.setOpenId(bindPhoneVo.getOpenId());
			sysUserService.updateById(sysUser);
			HashMap<String, Object> map = new HashMap<>();
			map.put("id", sysUser.getId());
			map.put("username", sysUser.getUsername());
			String token = JwtUtils.create(map);
			return Result.success(token);
		} else {
			return Result.fail("手机号不存在，请联系管理员修改");
		}
	}
}
